package main

import (
	"fmt"
)

// 返回一个error
func errorOutPut() error {
	var sex string
	fmt.Scanln(&sex)
	if sex != "男" && sex != "女" {
		return fmt.Errorf("录入性别既不是男，也不是女")
	}
	return nil
}
// recover抓住异常
func tryRecover() {
	defer func() {
		r := recover()
		if r == nil {
			fmt.Println("Nothing to recover. " +
				"Please try uncomment errors " +
				"below.")
			return
		}
		if err, ok := r.(error); ok {
			fmt.Println("Error occurred:", err)
		} else {
			panic(fmt.Sprintf(
				"I don't know what to do: %v", r))
		}
	}()

	// Uncomment each block to see different panic
	// scenarios.
	// Normal error
	//panic(errors.New("this is an error"))

	// Division by zero
	b := 0
	a := 5 / b
	fmt.Println(a)

	// Causes re-panic
	//panic(123)
}

func panicAndRecover() {

	var nameScore map[string]int
	nameScore["进文"] = 100
}

func main() {

	// defer只关注最外层的func,而不关注函数里面做的事情
	defer coverPanic()         // 这个defer抓不住
	defer coverPanicUpgraded() // 这个defer能抓住
	defer func() { // 这个也抓不住
		coverPanicUpgraded()
	}()
	panicAndRecover()
	//tryRecover()
}

func coverPanicUpgraded() {
	if r := recover(); r != nil {
		fmt.Println("panic and recover 出现错误：", r)
	}
}
func coverPanic() {
	func() {
		if r := recover(); r != nil {
			fmt.Println("panic and recover 出现错误：", r)
		}
	}()
}
